package smartt.styy.auth.biz;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;
import smartt.styy.auth.constants.ServerConstants;
import smartt.styy.auth.mapper.TbAuUserMapper;
import smartt.styy.auth.model.bean.UserInfoVo;
import smartt.styy.auth.model.entity.TbAuUser;
import smartt.styy.auth.model.request.UserTermDeviceEntity;
import smartt.styy.auth.util.IdGenerator;
import smartt.styy.common.bean.AnonymousInfo;
import smartt.styy.common.biz.BaseBiz;
import smartt.styy.common.constant.RestCodeConstants;
import smartt.styy.common.exception.BaseException;

@Service
@Slf4j
public class UserBiz extends BaseBiz<TbAuUserMapper, TbAuUser> {

	@Autowired
	private IdGenerator idGenerator;
	
	public TbAuUser selectUserInfoByParams(Map<String,Object> reqMap){
		List<TbAuUser> list = mapper.selectUserInfoByParams(reqMap);
		if(list == null || list.size() == 0){
			return null;
		}
		return list.get(0);
	}
	
	
	public TbAuUser selectByUserName(String username){
		return mapper.selectByUserName(username);
	}
	
	public List<UserInfoVo> getUserInfoQuery(Map<String,Object> reqMap){
		return mapper.getUserInfoQuery(reqMap);
	}
	
	
	//匿名用户注册
	public AnonymousInfo loginByTerm(UserTermDeviceEntity param){
		AnonymousInfo anonymous =new AnonymousInfo();
		TbAuUser auUser = null;
		try {
			Map<String,Object> reqMap = new HashMap<String,Object>();
			reqMap.put("username", param.getMobileImei());
			reqMap.put("anonymous", ServerConstants.ANONYMOUS);
			TbAuUser userEntity = selectUserInfoByParams(reqMap);
			if(userEntity == null){
				auUser = new TbAuUser();
				auUser.setUsername(param.getMobileImei());
				auUser.setAnonymous(ServerConstants.ANONYMOUS);
				auUser.setNickName(idGenerator.nextId());
				mapper.insertSelective(auUser);
				anonymous.setId(auUser.getId());
			}else{
				auUser = new TbAuUser();
				auUser.setUpdateAt(new Date());
				auUser.setAnonymous(ServerConstants.ANONYMOUS);
				mapper.updateByPrimaryKeySelective(auUser);
				anonymous.setId(userEntity.getId());
			}
			anonymous.setNickName(auUser.getNickName());
			anonymous.setUsername(param.getMobileImei());
		} catch (Exception e) {
			log.error("[UserBiz][loginByTerm]，匿名用户登录异常，错误信息message:"+e.getMessage());
			throw new BaseException("[UserBiz][loginByTerm]，匿名用户登录异常，错误信息message:"+e.getMessage(),RestCodeConstants.TOKEN_ERROR_CODE);
		}
		return anonymous;
	}
	
}
